// const app = getApp()
var app = getApp()
const db = wx.cloud.database()
Page({
  data: {
    userInfo: {},
    flag1: false,
    flag2: false,
    apply: false,
    realkeyWords: [],
    contleft: 0,
    contmaxwidth: 0
  },
  onLoad() {
    console.log(app.globalData.myselfflag);

    //检查是否在log里面 如果在的话就是apply true //然后赋值avatar,Info
    if (app.globalData.myselfflag) {
      this.checkUserAuthStatus();
      app.globalData.myselfflag = false;
    }
    this.seamless([
      "宿窝窝",
      "就是很厉害",
      "公主请喝水",
      "公主请学习",
      "公主请睡觉",
      "来抽奖吧",
      "今天的大作业写完了吗",
      "你今天过得好吗",
      "今天吃什么",
      "祝你今天特别特别开心",
      "嘎嘎嘎",
      "今天你上号了吗",
      "今天也想吃关东煮",
      "羊杂面YYDS",
      "为什么期末这么难",
      "受不了了",
      "好饿啊",
      "好困啊 ",
      "蝶蝶子",
      "哒哒哒哒"
    ]);
  },
  //退出登录
  // 退出
  loginOut(options) {
    this.setData({
      apply: false,
    })
    wx.setStorageSync('userInfo', null); //保存用户信息到本地缓存。相当于session

    console.log("调用退出");
  },


  //获取用户信息
  getUserProfile(e) {
    wx.getUserProfile({
      desc: '用于完善资料',
      success: (res) => {
        console.log(res.userInfo);
        this.setData({
          apply: true,
          userInfo: res.userInfo,
        })
        this.addUserAuthStatus(); // 检查并保存用户信息到亚马逊数据库
      },
      fail: res => {
        console.log("获取用户信息失败", res)
      }
    })
  },

  // 用户选择头像
  onChooseAvatar(e) {
    console.log(e.detail);
    const {
      avatarUrl
    } = e.detail;
    console.log(avatarUrl);
    this.setData({
      ['userInfo.avatarUrl']: avatarUrl,
    });
    let suffix = /\.[^\.]+$/.exec(avatarUrl); // 正则表达式，获取文件扩展名
    const openid = app.globalData.openid;
    wx.cloud.uploadFile({
      cloudPath: new Date().getTime() + suffix,
      filePath: avatarUrl, // 从 e.detail 中获取的本地文件路径
      success: res => {
        console.log('上传成功', res.fileID); // 上传成功后返回的文件 ID
        // 使用返回的 fileID 更新数据库中用户的头像
        const db = wx.cloud.database();
        db.collection("userInfo").where({
            openid: openid
          }).update({
            data: {
              avatar: res.fileID
            }
          })
          .then(() => {
            console.log('成功更新头像');
          })
          .catch((error) => {
            console.error('更新头像失败', error);
          });
      },
      fail: error => {
        console.error('上传失败', error);
      }
    });
  },


  // 用户修改昵称
  changeNickName(e) {
    let name = e.detail.value;
    if (name.length === 0) return;
    this.setData({
      ['userInfo.nickName']: e.detail.value
    })
    const openid = app.globalData.openid;
    db.collection("userInfo").where({
        openid: openid
      }).update({
        data: {
          name: e.detail.value
        }
      })
      .then(() => {
        console.log('成功更新昵称');
      })
      .catch((error) => {
        console.error('更新昵称失败', error);
      });
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */

  onShow(options) {},

  checkUserAuthStatus() {
    const openid = app.globalData.openid;
    db.collection('log').where({
      openid: openid
    }).get().then(res => {
      console.log(openid);

      if (res.data.length > 0) {
        console.log('用户已授权登录');
        db.collection('userInfo').where({
          openid: openid
        }).get().then(result => {
          console.log(openid);
          if (result.data.length > 0) {
            const userDetail = result.data[0];
            this.setData({
              apply: true,
              userInfo: {
                nickName: userDetail.name,
                avatarUrl: userDetail.avatar
              }
            });
          } else {
            console.log('userInfo未找到用户信息');
          }
        }).catch(error => {
          console.error('获取用户信息失败', error);
        });
      } else {
        console.log('用户尚未授权登录');
      }
    });
  },


  addUserAuthStatus() {
    const openid = app.globalData.openid;
    db.collection('log').where({
      openid: openid
    }).get().then(res => {
      console.log(openid);

      if (res.data.length > 0) {
        console.log('用户已授权登录');
        db.collection('userInfo').where({
          openid: openid
        }).get().then(result => {
          console.log(openid);
          if (result.data.length > 0) {
            const userDetail = result.data[0];
            this.setData({
              apply: true,
              userInfo: {
                nickName: userDetail.name,
                avatarUrl: userDetail.avatar
              }
            });
          } else {
            console.log('userInfo未找到用户信息');
          }
        }).catch(error => {
          console.error('获取用户信息失败', error);
        });
      } else {
        console.log('用户尚未授权登录');
        console.log(openid);
        db.collection('log').add({
          data: {
            openid: openid,
          }
        }).then(() => {
          console.log('用户信息保存成功');
          this.setData({
            apply: true
          });
        }).catch(error => {
          console.error('用户信息保存失败', error);
        })
        db.collection('userInfo').where({
          openid: openid
        }).get().then(result => {
          const userDetail = result.data[0];
          this.setData({
            apply: true,
            userInfo: {
              nickName: userDetail.name,
              avatarUrl: userDetail.avatar
            }
          });
        }).catch(error => {
          console.error('获取用户信息失败', error);
        });
      }
    });
  },
  advice: function () {
    wx.navigateTo({
      url: '/pages/advice/advice'
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },
  seamless(keyWords) {
    let that = this;
    //372rpx  三行每一行的top
    var row = [0, 124, 248];
    var margin = 30; //30rpx 项目的left间距
    var fontsize = 36; //36rpx 字体大小用来计算宽度

    var arrswidth = [0, 0, 0]; //三行每一项的宽度值
    var realkeyWords = [ //计算好的可用数组
      // {val:"我去局,输",top:0,left:0}
    ];
    //刷新间隔(单位：ms)
    var interval = 30;
    //瀑布流计算
    //xxxrpx*设备宽度/750
    wx.getSystemInfo({
      success: function (res) {
        row = [0 * res.windowWidth / 750, 124 * res.windowWidth / 750, 248 * res.windowWidth / 750];
        margin = 30 * res.windowWidth / 750;
        fontsize = 36 * res.windowWidth / 750;
        for (var i = 0; i < 3; i++) {
          realkeyWords.push({
            val: keyWords[i],
            top: row[i],
            left: margin,
            width: (keyWords[i].length + 2) * fontsize
          });
          arrswidth[i] = margin + (keyWords[i].length + 2) * fontsize;
        };
        for (var i = 3; i < keyWords.length; i++) {
          var minval = Math.min.apply(null, arrswidth);
          var minindex = 0;
          for (var j = 0; j < arrswidth.length; j++) {
            if (minval == arrswidth[j]) {
              minindex = j;
              break;
            };
          };
          var str = keyWords[i];
          realkeyWords.push({
            val: str,
            top: row[minindex],
            left: margin + minval,
            width: (str.length + 2) * fontsize
          });
          arrswidth[minindex] = arrswidth[minindex] + margin + (str.length + 2) * fontsize;
        };

        var contmaxwidth = Math.ceil(Math.max.apply(null, arrswidth));
        console.log("item值", realkeyWords, "最大宽度", contmaxwidth);
        that.setData({
          realkeyWords: realkeyWords,
          contmaxwidth: contmaxwidth
        });
        that.wfgdTimer = setInterval(function () {
          if (that.data.contleft <= -contmaxwidth) {
            that.setData({
              contleft: 0
            });
          } else {
            that.setData({
              contleft: that.data.contleft - 1
            });
          };
        }, interval);
        //e
      }
    });
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }

})